<script setup>
// 路由
const router = useRouter()
// 用户store
const userStore = useUserStore()

// 表单数据
const oldPassword = ref('')
const newPassword = ref('')
const confirmPassword = ref('')

// 修改密码API
const { runAsync: changePassword, loading } = changePasswordApi()

// 自定义校验规则：确认密码
const validateConfirmPassword = value => {
  if (!value) return '请再次输入新密码'
  if (value !== newPassword.value) return '两次输入的新密码不一致'
  return true
}

// 自定义校验规则：新密码不能与旧密码相同
const validateNewPassword = value => {
  if (!value) return '请填写新密码'
  if (value === oldPassword.value) return '新密码不能与原密码相同'
  return true
}

// 修改密码方法
const handleChangePassword = async () => {
  try {
    const encryptedOldPassword = md5EncryptWithSalt(oldPassword.value)
    const encryptedNewPassword = md5EncryptWithSalt(newPassword.value)
    // 调用修改密码API
    await changePassword({
      oldPassword: encryptedOldPassword,
      newPassword: encryptedNewPassword
    })

    showToast('密码修改成功，请重新登录')

    // 修改成功后退出登录
    userStore.logout()

    // 跳转到登录页
    router.replace('/login')
  } catch (error) {
    console.error('修改密码失败:', error)
    showToast(error?.message || '修改密码失败，请重试')
  }
}

// 检查是否已登录，未登录则跳转到登录页
// if (!userStore.hasLogin) {
//   router.replace('/login');
// }
</script>

<template>
  <div class="min-h-screen bg-gray-100 bg-white">
    <van-nav-bar title="修改密码" left-arrow @click-left="router.back()" />

    <div class="w-full mt-10 p-4">
      <van-form @submit="handleChangePassword">
        <van-cell-group inset>
          <van-field
            v-model="oldPassword"
            type="password"
            name="oldPassword"
            label="原密码"
            placeholder="请输入原密码"
            :rules="[{ required: true, message: '请填写原密码' }]"
          />
          <van-field
            v-model="newPassword"
            type="password"
            name="newPassword"
            label="新密码"
            placeholder="请输入新密码"
            :rules="[{ validator: validateNewPassword }]"
          />
          <van-field
            v-model="confirmPassword"
            type="password"
            name="confirmPassword"
            label="确认新密码"
            placeholder="请再次输入新密码"
            :rules="[{ validator: validateConfirmPassword }]"
          />
        </van-cell-group>

        <div class="mt-8 px-4">
          <BaseButton round block type="primary" native-type="submit" :loading="loading">
            确认修改
          </BaseButton>
        </div>
      </van-form>
    </div>
  </div>
</template>
<route>
  { 
    path: '/change-password',
    name: 'change-password',
    meta: {
      title: '修改密码',
      hideTabbar: true,
    }
  }
</route>
